package com.chen.common.satoken.controller;

import cn.dev33.satoken.annotation.SaIgnore;
import cn.dev33.satoken.sso.model.SaCheckTicketResult;
import cn.dev33.satoken.sso.processor.SaSsoClientProcessor;
import cn.dev33.satoken.sso.template.SaSsoUtil;
import cn.dev33.satoken.stp.StpUtil;
import com.chen.root.base.R;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * Sa-Token-SSO Client端 Controller
 * @author ChenJinLong
 */
@Slf4j
@SaIgnore
@RestController
@RequestMapping("/sso/client")
public class SsoClientController {

    @PostMapping("/login")
    @ApiOperation(value = "登录地址", tags = "登录地址")
    public Object ssoLogin() {
        return SaSsoClientProcessor.instance.ssoLogin();
    }

    @RequestMapping("/logout")
    @ApiOperation(value = "注销地址", tags = "注销地址")
    public Object ssoLogout() {
        return SaSsoClientProcessor.instance.ssoLogout();
    }

    @PostMapping("/logoutCall")
    @ApiOperation(value = "单点注销回调接口", tags = "单点注销回调接口")
    public Object ssoLogoutCall() {
        return SaSsoClientProcessor.instance.ssoLogoutCall();
    }

    @PostMapping("/getSsoAuthUrl")
    @ApiOperation(value = "返回SSO认证中心登录地址", tags = "返回SSO认证中心登录地址")
    public R<String> getSsoAuthUrl(String clientLoginUrl) {
        String serverAuthUrl = SaSsoUtil.buildServerAuthUrl(clientLoginUrl, "");
        return R.ok(serverAuthUrl);
    }

    @PostMapping("/doLoginByTicket")
    @ApiOperation(value = "根据ticket进行登录", tags = "根据ticket进行登录")
    public R<String> doLoginByTicket(String ticket) {
        SaCheckTicketResult ctr = SaSsoClientProcessor.instance.checkTicket(ticket, "/sso/client/doLoginByTicket");
        StpUtil.login(ctr.loginId, ctr.remainSessionTimeout);
        return R.ok(StpUtil.getTokenValue());
    }

}
